<template>
  <div class="voice-message-box">
    <p class="title">语音识别消息列表</p>
    <ul class="receive-msg-list">
      <li class="msg-li" v-for="(item, index) in receiveData" :key="index">
        <p>时间： {{ timestampToTimeFn(item.time) }}</p>
        <p>内容： {{ item.content }}</p>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, reactive , onMounted,onUnmounted} from 'vue'
import { generateRandomLetters, timestampToTime } from '../utils/util.js'
const path = ref('wss://echo.websocket.org')
let ws = ref(null)
let receiveData = reactive([])

const init = () => {
  // 区分车端访问还是远程访问 
  // 车端 ： 用81端口;
  // 远程： 浏览器端口 + 1
  let wsHost = window.location.hostname
  let wsPort = window.location.port == '' ? 81 : Number(window.location.port) + 1
  path.value = `ws://${wsHost}:${wsPort}`
  // 实例化socket 
  try {
    ws.value = new WebSocket(path.value)
    ws.value.binaryType = 'arraybuffer';
  } catch (error) {
    console.error(`Failed to establish a connection: ${error}`);
    // 失败后重连
    setTimeout(() => {
      init();
    }, 1000);
    return;
  }
  //监听是否连接成功
  ws.value.onopen = () => {
  }

  //接听服务器发回的信息并处理展示
  ws.value.onmessage = (data) => {
    if (data.data) {
      let msg = JSON.parse(data.data)
      let obj = {
        time: parseInt(msg.time),
        content: msg.content
      }
      receiveData.unshift(obj)
    }
  }

  //监听连接关闭事件
  ws.value.onclose = () => {
    //监听整个过程中websocket的状态
    // console.log('ws连接状态：' + ws.value.readyState);
  }

  //监听并处理error事件
  ws.value.onerror = function (error) {
    // console.log(error);
  }
}

const timestampToTimeFn = (time) => {
  return timestampToTime(time)
}

onMounted(() => {
  init()
})
onUnmounted(() => {
  if (ws.value) {
    ws.value.onclose = undefined;
    ws.value.close()
  }
});
</script>

<style lang="scss" scoped>
.voice-message-box {
  .title {
    // text-align: center;
    // background: rgb(3, 68, 96);
    height: 48px;
    line-height: 48px;
    font-size: 0.9rem;
    color: #333;
  }

  .receive-msg-list {
    height: 300px;
    overflow: auto;

    .msg-li {
      border-bottom: 1px solid #ddd;
      margin-bottom: 10px;
      padding: 10px;
    }
  }
}
</style>